package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.TimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 *
 * @date 2025-10-24
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private IFamilyMemberService familyMemberService;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void cancelReservation(Long id) {
        LambdaUpdateWrapper<Reservation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Reservation::getId, id)
                .set(Reservation::getStatus, 2)
                .set(Reservation::getUpdateTime, DateUtils.getNowDate());
        update(updateWrapper);
    }

    @Override
    public void saveReservation(Reservation reservation) {
        Long userId = UserThreadLocal.get();
        FamilyMember familyMember = familyMemberService.getById(userId);
        String mobile = familyMember.getPhone();
        Integer cancell = reservationMapper.cancelled(mobile);

        if (cancell > 3) {
            throw new BaseException("取消次数已达上限");
        } else {
            // 判断时间
            List<TimeVo> list = reservationMapper.countByTime();
            for (TimeVo timeVo : list) {
                Integer count = 5 - timeVo.getCount();
                String time = timeVo.getTime ();
                LocalDateTime dateTime = LocalDateTimeUtil.parse(time, "yyyy-MM-dd HH:mm:ss");
                LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Reservation::getTime , reservation.getTime());
                List<Reservation> list1 = this.list(queryWrapper);
                if (CollUtil.isEmpty(list1)) {
                    this.save(reservation);
                }
//                if (timeVo.getTime().isEmpty()) {
//                    this.save(reservation);
//                }
                if (dateTime.isEqual(reservation.getTime())) {
                    if (count > 0) {
                        this.save(reservation);
                    } else {
                        throw new BaseException("该时间预约人数已满");
                    }
                }
            }
        }

    }

    @Override
    public Integer cancelled(Long userId) {
        FamilyMember familyMember = familyMemberService.getById(userId);
        String mobile = familyMember.getPhone();
        Integer time = reservationMapper.cancelled(mobile);
        return time;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<TimeVo> countByTime(LocalDateTime localDateTime) {
        List<TimeVo> list = reservationMapper.countByTime();
        List<TimeVo> timeVos = new ArrayList<>();
        for (TimeVo timeVo : list) {
            TimeVo vo = new TimeVo();
            Integer count = timeVo.getCount();
            if (count >= 0 && count <= 6) {
                vo.setCount(6 - count);
                vo.setTime(timeVo.getTime());
                timeVos.add(vo);
            } else {
                vo.setCount(0);
                vo.setTime(timeVo.getTime());
                timeVos.add(vo);
            }
        }
        return timeVos;
    }

    @Override
    public List<Map> selectcountByTime(Long time) {
        String Counttime="8:00,8:30,9:00,9:30,10:00,10:30,11:00,11:30,12:00,12:30,13:00,13:30,14:00,14:30,15:00,15:30,16:00,16:30,17:00,17:30,18:00";
        int countTime=6;
        List<String> split = Arrays.asList(Counttime.split(","));
        // Long time1=15897600000L;
        Long newTime=time;
        Instant instant = Instant.ofEpochMilli(newTime);
        LocalDateTime time2 = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        LocalDate localDate = time2.toLocalDate();
        String string1 = localDate.toString();
        List<Map> list =new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'H:mm");
        for (String string : split) {
            String timeMapper=string1 +"T"+string;
            LocalDateTime localDateTime = LocalDateTime.parse(timeMapper,dateTimeFormatter);
            LambdaUpdateWrapper<Reservation> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Reservation::getTime,localDateTime);
            // 0：待报道，1：已完成，2：取消，3：过期'
            lambdaUpdateWrapper.eq(Reservation::getStatus,0);
            List<Reservation> list1 = this.list(lambdaUpdateWrapper);
            Map map =new HashMap();
            if (list1.size()>0) {
                int timeCount=countTime- list1.size();
                if (timeCount<=0) {
                    timeCount=0;
                }
                map.put("time",localDateTime);
                map.put("count",timeCount);
            }
            list.add(map);
        }
        return list;
    }
}



